const Constants = {
    SUBSCRIBE_INFO: 2000,
    SUBSCRIBE: 2001,
    UNSUBSCRIBE: 2002,
    PUBLISH_EVENT: 2003,
};

const getParams = function (code) {
    return {
        messageCode: code,
        bundleName: 'com.chinasoftinc.facommon',
        abilityName: 'com.chinasoftinc.facommon.EventInternalAbility',
        abilityType: 1,
        syncOption: 0,
        data: code,
    };
};

const TAG = 'EventUtils'

export default {
    subscribeIng: false,

    /**
     * 订阅消息
     * @key 订阅消息对象的标识, 用于定位区分对象
     * @subscribeEventTypes 订阅消息的事件类型, 数组类型 , 如 ["start","shutdown"], 传 [] 表示关注所有类型事件
     * @param eventCallback 消息回调
     * @param failedCallback 订阅失败回调
     * @param successCallback 订阅成功回调
     */
    async subscribeEvent(key, subscribeEventTypes, eventCallback, failedCallback, successCallback) {
        if (this.subscribeIng) {
            failedCallback('The server is processing last request, Please wait')
            return
        }
        this.subscribeIng = true;
        let subInfoParams = getParams(Constants.SUBSCRIBE_INFO);
        subInfoParams.data = {
            "key": key,
            "subscribeEventTypes": subscribeEventTypes,
        }
        FeatureAbility.callAbility(subInfoParams).then(result => {
            let params = getParams(Constants.SUBSCRIBE);
            FeatureAbility.subscribeAbilityEvent(params, eventCallback)
                .then(value => {
                    successCallback()
                    this.subscribeIng = false;
                    console.log(`${TAG} subscribeEven.then: ${JSON.stringify(value)}`)
                })
                .catch(err => {
                    failedCallback(err)
                    this.subscribeIng = false;
                    console.log(`${TAG} subscribeEven.catch: ${JSON.stringify(err)}`)
                })
        }).catch(err => {
            failedCallback(err)
            this.subscribeIng = false;
        })
    },

    /**
     * 取消订阅消息, 当页面退出时应及时调用该方法以节省资源
     * @param callback 消息回调
     */
    async unsubscribeEvent(key) {
        let params = getParams(Constants.UNSUBSCRIBE);
        params.data = {
            "key": key
        }
        FeatureAbility.unsubscribeAbilityEvent(params)
    },


    /**
     * 发布消息
     * @param type 事件的类型, 字符串类型
     * @param data 携带的事件, 字符串类型, 可为json格式
     * @param code 事件的标识码, 默认为0
     */
    async publishEvent(type, data, code=0) {
        let params = getParams(Constants.PUBLISH_EVENT);
        params.data = {
            "type": type,
            "data": data,
            "code": code
        }
        return await FeatureAbility.callAbility(params)
    },
}